<?php
/**
 * @标签类
 * 1、招商地图
 * 2、省市区对应下面的企业或者园区的数量统计
 * 3、产业链（二维）下节点的数量统计
 * 4、下级产业链下节点的数量统计
 * 5、热力图
 * @作者 
 * 万全强（php）
 */
namespace app\controller;

use app\controller\HomeBase;
use think\facade\Db;

use app\model\AdminRole;
use app\model\Chain;
use app\model\CityModel;
use app\model\CompanyModel;
use app\model\ParkModel;



use app\libs\Predis;





class Map extends HomeBase
{

	private $CompanyModel;
	private $ParkModel;
	private $ChainModel;
    public function __construct(){
               
        parent::__construct();
        $this->CompanyModel=new CompanyModel();
        $this->ParkModel=new ParkModel();
        $this->ChainModel=new Chain();
    }
    /**
     * 1、招商地图
     */
    public function GetBusinessMap(){
        /***城市*/
    	$city_id = request()->param('city_id', 1, 'intval');
    	/**产业链**/
        $chain_id = request()->param('chain_id', 0, 'intval');


        $cache = new Predis();
        $data=$cache->get('MapBusiness_'.$chain_id.'_'.$city_id);
        if($data){
            $result=unserialize($data);
            return json(['status' => 1, 'msg' => '获取成功', 'data' => $result]);
        }


        $type=1;
        $AdminRole=new AdminRole();
        $RoleChain=new Chain();

        $ChainDetail=$RoleChain->GetChainDetail($chain_id);

        if(empty($ChainDetail)){
            return json(['status'=>0,'msg'=>'该产业链不存在','data'=>[]]);
        }

        $CityModel=new CityModel();
        $city=$CityModel->GetChildren($city_id);


         //p($ChainDetail->pid);
        //大节点产业链
        if($ChainDetail['pid']==0){
            $role_ids=$AdminRole->GetRole($this->user_id);
            if(!empty($role_ids)){
                $Chain=$RoleChain->GetChain($role_ids[0],"id!=$chain_id");//当前产业链
                $Chain=arr2tree($Chain,$chain_id,'chain_name');
                $Chain=imp($Chain);
               
                $searchParams['index'] = config('app.elasticsearch')['CompanyIndex'];
                $searchParams['type'] = config('app.elasticsearch')['type'];
                //p($city);               
                $result=[];              
                $i=0;
                
                foreach ($Chain as $key=>$val){
                    $datas=[];
                    $total=0;
                    $j=0;
                    foreach ($city as $key1=>$val1){
                        //p($val1);
                    	$condition=[];
                    	$condition['chain_id']=$val['insertid'];
                    	$condition['city_id']=$val1['id'];
                    	$condition['range']=[
                    			'score'=>[
                    					'gte'=>60,
                    					'lte'=>100
                    			]
                    	];
                    	$field=['company_name','score','identification'];
                    	
                    	$retDoc=$this->CompanyModel->GetList($field,$condition,1,3,['score'=>'desc']);
                    	if($retDoc['total']==0){
                            continue;
                        }
                        $list=[];               
                        if($retDoc['total']!=0&&$retDoc['data']){
                        	foreach ($retDoc['data'] as $key2=>$val2){
                                $list[$key2]['CompanyName']=$val2['company_name'];
                                $list[$key2]['Score']=$val2['score'];
                                $list[$key2]['identification']=$val2['identification'];
                            }
                        }
                        $total+=$retDoc['total'];
                        $datas[$j]['id']=$val1['id'];
                        $datas[$j]['CityName']=$val1['city_name'];
                        $datas[$j]['CompanyNum']=$retDoc['total'];
                        $datas[$j]['Company']=$list;
                        $j++;
                        
                    }
                    if($total==0){
                        continue;
                    }
                    $re=bubble_sort($datas,'CompanyNum');
                    
                    $result[$i]['ChainName']=$val['chain_name'];
                    $result[$i]['CompanyNum']=$total;
                    $result[$i]['City']=$re;
                    $i++;
                    if(count($result)>=20){
                        break;
                    }
                }  	
                $result=bubble_sort($result,'CompanyNum');              
            }  
        //小节点
        }else{
            $type=2;
            $datas=[];
            $j=0;
            foreach ($city as $key=>$val1){
                //p($val1);
            	//p($val1);
            	$condition=[];
            	$condition['chain_id']=$ChainDetail->id;
            	$condition['city_id']=$val1['id'];
            	$condition['range']=[
            			'score'=>[
            					'gte'=>60,
            					'lte'=>100
            			]
            	];
            	$field=['company_name','score','identification'];
            	$retDoc=$this->CompanyModel->GetList($field,$condition,1,12,['score'=>'desc']);
            	
            	if($retDoc['total']==0){
                    continue;
                }
                $list=[];               
                if($retDoc['total']!=0&&$retDoc['data']){
                	foreach ($retDoc['data'] as $key2=>$val2){
                        $list[$key2]['CompanyName']=$val2['company_name'];
                        $list[$key2]['Score']=$val2['score'];
                        $list[$key2]['identification']=$val2['identification'];
                    }
                }
                $datas[$j]['id']=$val1['id'];
                $datas[$j]['CityName']=$val1['city_name'];
                $datas[$j]['CompanyNum']=$retDoc['total'];
                $datas[$j]['Company']=$list;
                $j++;
                
            }
            $result=bubble_sort($datas,'CompanyNum');
            
        }
        
        $cache->set('MapBusiness_'.$chain_id.'_'.$city_id,serialize(['type'=>$type,'data'=>$result]),3600);	
    	return json(['status' => 1, 'msg' => '获取成功', 'data' => ['type'=>$type,'data'=>$result]]);
    }
    /**
     * 2、省市区对应下面的企业或者园区的数量统计
     */
    public function CompayOrParkNumOnMap(){
    	$yun_chain_id=request()->param('yun_chain_id', 0, 'intval');
    	$chain_id=request()->param('chain_id', 0, 'intval');
    	$city_id=request()->param('city_id', 1, 'intval');
    	$type=request()->param('type', 'company', 'trim');
    	
    	
    	$this->CityModel=new CityModel();
    	$res=$this->CityModel->GetDetail($city_id);
    	
    	
    	if(isset($res['type'])&&$res['type']==3){
    		
    		$condition=[];
    		$condition['yun_chain_id']=$yun_chain_id;
    		$condition['chain_id']=$chain_id;
    		$condition['city_id']=$res['id'];
    		$condition['user_id']=$this->user_id;
    		
    		if($type=='company'){
    			//$result=$this->CompanyModel->GetTotal($condition);
    			$res=$this->CompanyModel->GetList(['identification','company_name','score','lat','lng'],$condition);
    			$result=$res['data'];
    			//p($result);
    		}
    		
    		if($type=='park'){
    			//$result=$this->ParkModel->GetTotal($condition);
    			$res=$this->ParkModel->GetList(['identification','park_name','lat','lng'],$condition);
    			$result=$res['data'];
    		}
    		
    	}else{
    		$result=$this->CityModel->GetInfo($city_id);
    		
    		foreach ($result as $key=>&$val){
    			$condition=[];
    			$condition['yun_chain_id']=$yun_chain_id;
    			$condition['chain_id']=$chain_id;
    			$condition['city_id']=$val['id'];
    			$condition['user_id']=$this->user_id;
    			if($type=='company'){
    				$val['total']=$this->CompanyModel->GetTotal($condition);
    				$val['data']=$this->CompanyModel->GetList(['identification','company_name','score'],$condition); 				
    			}
    			
    			if($type=='park'){
    				$val['total']=$this->ParkModel->GetTotal($condition);
    				
    				$val['data']=$this->ParkModel->GetList(['identification','park_name'],$condition);				
    			}
    			
    			unset($val['children']);
    		}
    	}
    	
    	//p($result);
    	
    	
    	
    	return json(['status'=>1,'msg'=>'获取成功','data'=>$result]);
    
    }
    /**
     * 3、产业链下节点的数量统计
     */
    public function CompanyNumOnChain(){
    	$chain_id=request()->param('chain_id', 0, 'intval');
    	$city_id=request()->param('city_id', 1, 'intval');
    	
    	$cache = new Predis();
    	$data=$cache->get('CompanyNumOnChain_'.$chain_id.'_'.$city_id);
    	if($data&&1==2){
    		$result=unserialize($data);
    		return json(['status' => 1, 'msg' => '获取成功', 'data' => $result]);
    	}
    	
    	$Chain=[];
    	if($this->user_id){
    		$RoleChain=new Chain();
    		$AdminRole=new AdminRole();
    		$role_ids=$AdminRole->GetRole($this->user_id);
    		
    		if(!empty($role_ids)){
    			$res=$RoleChain->GetChain($role_ids[0],'1=1','id,chain_id,chain_name,pid');//当前产业链
    			$Chain=arr2tree($res,$chain_id,'chain_name','id');
    			$Chain=imp($Chain);
    			foreach ($Chain as &$val){
    				$condition=[];
    				$condition['chain_id']=$val['id'];
    				$condition['city_id']=$city_id;
    				$val['total']=$this->CompanyModel->GetTotal($condition);
    			}
    		}
    	}
    	$last_names = array_column($Chain,'total');
    	array_multisort($last_names,SORT_DESC,$Chain);
    	
    	$smallchain=[];
    	$bigchain=[];
    	if(isset($Chain[0])&&$Chain[0]['total']>0){
    		$bigchain[]=$Chain[0]['chain_name'];
    	}
    	if(isset($Chain[1])&&$Chain[1]['total']>0){
    		$bigchain[]=$Chain[1]['chain_name'];
    	}
    	if(isset($Chain[2])&&$Chain[2]['total']>0){
    		$bigchain[]=$Chain[2]['chain_name'];
    	}
    	
    	if(isset($Chain[count($Chain)-1])){
    		$smallchain[]=$Chain[count($Chain)-1]['chain_name'];
    	}
    	if(isset($Chain[count($Chain)-2])){
    		$smallchain[]=$Chain[count($Chain)-2]['chain_name'];
    	}
    	if(isset($Chain[count($Chain)-3])){
    		$smallchain[]=$Chain[count($Chain)-3]['chain_name'];
    	}
    	$messlist=[];
    	if($bigchain){
    		$messlist[]=['key'=>'强链','value'=>implode(',',$bigchain)];
    	}
    	if($smallchain){
    		$messlist[]=['key'=>'补链/延链','value'=>implode(',',$smallchain)];
    	} 
    	
    	$result=['data'=>$Chain,'messlist'=>$messlist];
    	$cache->set('CompanyNumOnChain_'.$chain_id.'_'.$city_id,serialize($result),3600);  	
    	return json(['status'=>1,'msg'=>'获取成功','data'=>$result]);  	
    }
    /**
     * 4、下级产业链下节点的数量统计
     */
    public function ChildrenCompanyNumOnChain(){
    	$chain_id=request()->param('chain_id', 0, 'intval');
    	$city_id=request()->param('city_id', 1, 'intval');
    	
    	$cache = new Predis();
    	$data=$cache->get('ChildrenCompanyNumOnChain_'.$chain_id.'_'.$city_id);
    	if($data&&1==2){
    		$result=unserialize($data);
    		return json(['status' => 1, 'msg' => '获取成功', 'data' => $result]);
    	}
    	
    	$Chain=[];
    	if($this->user_id){
    		$RoleChain=new chain();
    		$AdminRole=new AdminRole();
    		$role_ids=$AdminRole->GetRole($this->user_id);
    		
    		if(!empty($role_ids)){
    			$res=$RoleChain->GetChain($role_ids[0],'1=1','id,chain_id,chain_name,pid');//当前产业链
    			$Chain=arr2tree($res,$chain_id,'chain_name','id');
    			//$Chain=imp($Chain);
    			foreach ($Chain as &$val){
    				$condition=[];
    				$condition['chain_id']=$val['id'];
    				$condition['city_id']=$city_id;
    				$val['total']=$this->CompanyModel->GetTotal($condition);
    				unset($val['children']);
    			}
    		}
    	}
    	
    	$cache->set('ChildrenCompanyNumOnChain_'.$chain_id.'_'.$city_id,serialize($Chain),3600);
    	return json(['status'=>1,'msg'=>'获取成功','data'=>$Chain]);
    }
    /**
     * 5、企业热力图
     */
    public function GetCompanyHeat(){
    	$condition=[];
    	
    	$chain_id = request()->param('chain_id', 0, 'intval');
    	if (!empty($chain_id)) {
    		$condition['chain_id']=$chain_id;
    	}
    	$city_id = request()->param('city_id', 0, 'intval');
    	if (!empty($city_id)) {
    		$condition['city_id']=$city_id;
    	}
    	
    	$field=['location'];
    	
    	
    	$list=$this->CompanyModel->GetList($field,$condition,1,5000);
    	
    	$res=[];
    	foreach($list['data'] as $val){
    		$res[]=[$val['location'][0],$val['location'][1]];
    	}
    	return json(['status'=>1,'msg'=>'获取成功','data'=>$res]);
    }
}